<template>
  <div class="login-box" :class="{'login-reset-pssword': type === 'forgetPasword', 'login-sign-up': type === 'signup'}">
    <div class="login-logo"></div>
    <!-- 登录 -->
    <div class="login-content" v-if="type === 'login'">
      <ZTab v-model:navs="navs" v-model:active="navsActive" @change="changeTabs"/>
      <div class="z-content">
        <el-form :model="passwordForm" ref="passwordFormRef" :rules="passwordFormRules" class="demo-form-inline">
          <el-form-item prop="userName" v-if="!isPhoneLogin">
            <el-input autocomplete="off" v-model="passwordForm.userName" :placeholder="t('login.accountPls')" />
          </el-form-item>
          <el-form-item prop="userName" class="phone-form" v-else>
            <el-select v-model="passwordForm.area" size="large">
              <el-option
                v-for="item in langAreaList"
                :key="item.countryCode"
                :label="item.countryCode"
                :value="item.countryCode"
              >
                <div class="phone-area-option">
                  <img :src="item.resource" alt="">
                  <span>{{ item.countryCode }}</span>
                </div>
              </el-option>
            </el-select>
            <el-input autocomplete="off" v-model="passwordForm.userName" :placeholder="t('login.accountpho2')" />
          </el-form-item>
          <el-form-item prop="password" v-if="navsActive === 'withPassword'">
            <el-input autocomplete="off" v-model="passwordForm.password" :min="8" :max="16" type="password" show-password :placeholder="t('login.psdRule')" />
          </el-form-item>
          <el-form-item prop="code" v-if="navsActive === 'withCode'" class="form-input-code">
            <el-input autocomplete="off" v-model="passwordForm.code" :placeholder="t('login.verifiyInput')" />
            <el-button type="primary" size="large" @click="getCodeOfLogin" :disabled="getLoginCodeDisabled">{{ getLoginCodeTxt }}</el-button>
          </el-form-item>
          <el-form-item>
            <z-slider @change="sliderSucceedLogin" ref="sliderRef"/>
          </el-form-item>
          <el-form-item class="z-form-item-flex">
            <el-checkbox v-model="passwordForm.rememberPwd">{{ t('home.rememberPwd') }}</el-checkbox>
            <span class="reset-pssword-txt-btn" @click="forgetPassword">{{ t('WALLET.forgetPwd') }}?</span>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="large" @click="login" :disabled="!sliderLoginStatus" :loading="loading.passwordLoading">{{t('home.Signin')}}</el-button>
          </el-form-item>
        </el-form>
        <div class="login-or-tips">
          <span>{{ t('login.text_005') }}</span>
          <ul>
            <li @click="toPhone" v-if="isPhoneLogin"><img :src="images.email" alt=""></li>
            <li @click="toPhone" v-else><img :src="images.phone" alt=""></li>
            <li><img :src="images.google" alt=""></li>
            <li><img :src="images.fb" alt=""></li>
          </ul>
        </div>
        <div class="login-signup-toggle">
          {{ $t('login.text_006') }}<span @click="toggleSignAndLogin('signup')">{{ $t('home.Signup') }}</span>
        </div>
      </div>
    </div>
    <!-- 忘记密码 -->
    <Forgetpassword v-if="type === 'forgetPasword'" v-model:isPhoneLogin="isPhoneLogin" class="login-content" @back="type = 'login'"/>
    <!-- 注册 -->
    <div class="login-content sign-up" v-if="type === 'signup'">
      <div class="sign-up__title" v-if="!piniaSystem.getIsH5">{{t('home.Signup')}}</div>
      <el-form :model="signupForm" ref="signupFormRef" :rules="signupFormRules" class="demo-form-inline">
        <el-form-item prop="email" v-if="!isPhoneSign">
          <el-input autocomplete="off" v-model="signupForm.email" :placeholder="t('login.enterEmail')" />
        </el-form-item>
        <el-form-item prop="phone" class="phone-form" v-else>
          <el-select v-model="passwordForm.area" size="large">
            <el-option
              v-for="item in langAreaList"
              :key="item.countryCode"
              :label="item.countryCode"
              :value="item.countryCode"
            >
              <div class="phone-area-option">
                <img :src="item.resource" alt="">
                <span>{{ item.countryCode }}</span>
              </div>
            </el-option>
          </el-select>
          <el-input autocomplete="off" v-model="signupForm.phone" :placeholder="t('login.accountpho2')" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input autocomplete="off" v-model="signupForm.password" :min="8" :max="16" type="password" show-password :placeholder="t('login.psdRule')" />
        </el-form-item>
        <!-- <el-form-item prop="code" class="form-input-code">
          <el-input autocomplete="off" v-model="signupForm.code" placeholder="Approved by" />
          <el-button type="primary" size="large" @click="getCodeOfSignup" :disabled="getSignupCodeDisabled">{{ getSignupCodeTxt }}</el-button>
        </el-form-item> -->
        <el-form-item>
          <el-input autocomplete="off" v-model="signupForm.promote" :placeholder="t('login.promotepls')" />
        </el-form-item>
        <el-form-item>
          <z-slider @change="sliderSucceedSignup" ref="sliderRef"/>
        </el-form-item>
        <el-form-item class="z-form-item-flex z-form-item-long-checkbox">
          <el-checkbox v-model="signupForm.agreement" label="">
            {{ t('home.Agreement') }}
          </el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="large" @click="signup" :disabled="!sliderSignupStatus || !signupForm.agreement" :loading="loading.signupLoading">{{t('home.Signup')}}</el-button>
        </el-form-item>
      </el-form>
      <div class="login-or-tips">
        <span>{{ t('login.text_005') }}</span>
        <ul>
          <li @click="toPhoneSign" v-if="isPhoneSign"><img :src="images.email" alt=""></li>
          <li @click="toPhoneSign" v-else><img :src="images.phone" alt=""></li>
          <li><img :src="images.google" alt=""></li>
          <li><img :src="images.fb" alt=""></li>
        </ul>
      </div>
      <div class="login-signup-toggle">
        {{ $t('login.text_007') }}<span @click="toggleSignAndLogin('signin')">{{ $t('home.Signin') }}</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="Login">
import loginApi from '@/api/modules/login';
import playGoldApi from '@/api/modules/playGold';
import userinfoApi from '@/api/modules/userinfo';
import sportsApi from '@/api/modules/sports';
import userinfo from '@/store/userinfo';
import system from '@/store/system';
import { dealKeys } from '@/utils/aes';

const piniaUserinfo = userinfo();
const piniaSystem = system();
const emits = defineEmits(['loginSucceeded', 'changeType']);
const currentWallet:any = piniaUserinfo.getCurrentWallet;
const langAreaList:any = computed(()=>piniaSystem.getLangList);
console.log("langAreaList", langAreaList)
const { t } = useI18n();

const props = defineProps({
  type: {
    type: String,
    default: 'login'
  }
});
const images = reactive({
  phone: new URL('../../assets/images/login/phone.svg', import.meta.url).href,
  google: new URL('../../assets/images/login/google.svg', import.meta.url).href,
  fb: new URL('../../assets/images/login/fb.svg', import.meta.url).href,
  email: new URL('../../assets/images/login/email.svg', import.meta.url).href,
  success: new URL('../../assets/images/login/success.svg', import.meta.url).href,
});
const data: any = reactive({
  type: props.type,
  steps: [
    {
      label: computed(()=> t('login.verify1'))
    },
    {
      label: computed(()=> t('login.set'))
    },
    {
      label: computed(()=> t('login.success'))
    },
  ],
  navs: [
    {
      label: t('login.accountLogin'),
      active: 'withPassword',
    },
    {
      label: t('login.text_008'),
      active: 'withCode',
    },
  ],
  navsActive: 'withPassword',
  passwordForm: {
    password: localStorage.getItem('password'),
    userName: localStorage.getItem('userName'),
    area: piniaSystem.getLang.countryCode,
    rememberPwd: localStorage.getItem('rememberMe') === 'true' ? true : false
    // userName: "313051@gmail.com",
  },
  isPhoneLogin: false,
  isPhoneSign: false,
  passwordFormRef: null,
  passwordFormRules: {
    userName: [
      { required: true, message: computed(()=>isPhoneLogin ? t('login.text_010') : t('login.accountEnter')), trigger: 'blur' },
    ],
    password: [
      { required: true, message: computed(()=>t('login.psdRule')), trigger: 'blur' },
      { min: 8, max: 16, message: computed(()=>t('login.psdRule')), trigger: 'blur' },
    ],
    code: [
      { required: true, message: computed(()=>t('login.verifiyRule')), trigger: 'blur' },
    ],
  },
  resetPasswordFormRef: null,
  resetPasswordForm: {
    area: piniaSystem.getLang.countryCode,
  },
  resetPasswordFormRules: {
    userName: [
      { required: true, message: computed(()=>isPhoneLogin ? t('login.text_010') : t('login.accountEnter')), trigger: 'blur' },
    ],
    password: [
      { required: true, message: computed(()=>t('login.psdRule')), trigger: 'blur' },
      { min: 8, max: 16, message: computed(()=>t('login.psdRule')), trigger: 'blur' },
    ],
    code: [
      { required: true, message: computed(()=>t('login.verifiyRule')), trigger: 'blur' },
    ],
    newPassword: [
      { required: true, message: computed(()=>t('login.psdRule')), trigger: 'blur' },
      { min: 8, max: 16, message: computed(()=>t('login.psdRule')), trigger: 'blur' },
    ],
    newPasswordSure: [
      { required: true, message: computed(()=>t('login.psdRule')), trigger: 'blur' },
      { validator: (rule: any, value: any, callback: any) => {
        if (value === '') {
          callback(new Error(t('login.enterAgain')))
        } else if (value !== resetPasswordForm.value.newPassword) {
          callback(t('login.diffrencePsd'))
        } else {
          callback()
        }
      }, trigger: 'blur' },
    ],
  },
  loading: {
    passwordLoading: false,
    resetPasswordLoading: false,
    signupLoading: false,
  },
  disabled: {
    passwordDisabled: true
  },
  sliderLoginStatus: false,
  sliderRef: null,
  getLoginCodeTxt: t('home.PhoneGetCode'),
  getLoginCodeDisabled: false,
  getResetPasswordCodeTxt: t('home.PhoneGetCode'),
  getResetPasswordCodeDisabled: false,
  getSignupCodeTxt: t('home.PhoneGetCode'),
  getSignupCodeDisabled: false,
  stepActive: 1,
  sliderSignupStatus: false,
  signupForm: {
    agreement: true
  },
  signupFormRef: null,
  signupFormRules: {
    email: [
      { required: true, message: computed(()=>t('login.accountEnter')), trigger: 'blur' },
    ],
    phone: [
      { required: true, message: computed(()=>t('login.text_010')), trigger: 'blur' },
    ],
    password: [
      { required: true, message: computed(()=>t('login.psdRule')), trigger: 'blur' },
      { min: 8, max: 16, message: computed(()=>t('login.psdRule')), trigger: 'blur' },
    ],
  },
  keyId: "",
});

const {
  type,
  steps,
  navs,
  navsActive,
  passwordForm,
  isPhoneLogin,
  isPhoneSign,
  passwordFormRef,
  passwordFormRules,
  resetPasswordFormRef,
  resetPasswordForm,
  resetPasswordFormRules,
  loading,
  sliderLoginStatus,
  sliderRef,
  getLoginCodeTxt,
  getLoginCodeDisabled,
  stepActive,
  getResetPasswordCodeTxt,
  getResetPasswordCodeDisabled,
  getSignupCodeTxt,
  getSignupCodeDisabled,
  sliderSignupStatus,
  signupForm,
  signupFormRef,
  signupFormRules,
  keyId,
} = toRefs(data);

// 滑动验证成功
const sliderSucceedLogin = (val: Boolean) => {
  sliderLoginStatus.value = val;
}

// 活动验证成功
const sliderSucceedSignup = (val: Boolean) => {
  sliderSignupStatus.value = val;
}

// login登录
const login = () => {
  passwordFormRef.value.validate((valid:any, fields:any) => {
    if (valid && sliderLoginStatus.value) {
      loading.value.passwordLoading = true;
      loginForNormal();
    }else{
      // 重置 滑块 ?
      sliderRef.value.resetSlider();
    }
  });
}

// 邮箱和手机 登录切换
const toPhone = () => {
  isPhoneLogin.value = !isPhoneLogin.value;
}

// 邮箱和手机 注册切换
const toPhoneSign = () => {
  isPhoneSign.value = !isPhoneSign.value;
}

// 注册
const signup = () => {
  signupFormRef.value.validate((valid:any, fields:any) => {
    if (valid && sliderSignupStatus.value) {
      loading.value.signupLoading = true;
      emailSignUpForNoraml();
    }else{
      // 重置 滑块 ?
      sliderRef.value.resetSlider();
    }
  });
}

// 邮箱注册
const emailSignUpForNoraml = () => {
  console.log("进入注册")
  loginApi.registerUser({
    registerType: 1,
    ...signupForm.value
  }).then((response:any)=>{
    if(response.code === 200){
      // emits('loginSucceeded', true);
      // piniaUserinfo.setUserinfo(response.data);
      // piniaUserinfo.setHaslogged(true);
      // dealKeys(response.data.token.key);
      // queryUserWallet();
      // getUserVip();
      // getSportsByChannel();
    }
  }).finally(()=>{
    loading.value.signupLoading = false;
  });
}

// 登录 注册切换
const toggleSignAndLogin = (mark: string) => {
  if(mark === 'signin'){
    // console.log("跳登录")
    type.value = 'login'
  }else if(mark === 'signup'){
    // console.log("跳注册")
    type.value = 'signup'
  }
}

// 重置密码
const resetPassword = () => {
  resetPasswordFormRef.value.validate((valid:any, fields:any) => {
    if (valid) {
      loading.value.resetPasswordLoading = true;
      if(stepActive.value === 1){
        emailSendAuth();
      }else if(stepActive.value === 2){
        // 充值密码
        resetPasswordQuery();
      }
    }else{
      // 重置 滑块 ?
    }
  });
}

// 充值密码
const resetPasswordQuery = () => {
  userinfoApi.resetPassword({
    newPassword: resetPasswordForm.value.newPassword,
    userName: resetPasswordForm.value.userName,
    type: 1
  }).then((response:any)=>{
    if(response.code === 200){
      // 成功后跳转
      stepActive.value ++;
    }
  }).finally(()=>{
    loading.value.resetPasswordLoading = false;
  });
}

// 验证 验证码是否正确
const emailSendAuth = () => {
  loginApi.emailSendAuth({
    code: resetPasswordForm.value.code,
    email: resetPasswordForm.value.userName
  }).then((response:any)=>{
    if(response.code === 200){
      // 成功后跳转
      stepActive.value ++;
    }
  }).finally(()=>{
    loading.value.resetPasswordLoading = false;
  });
}

// 切换 tabs
const changeTabs = ({nav, index}: any) => {
  console.log(nav.active, index)
}

// 邮箱和密码登录
const loginForNormal = () => {
  let loginTypeApi:any = loginApi.login;
  let loginObj = {
    ...passwordForm.value,
    loginType: 1,
  };
  if(navsActive.value === 'withPassword'){
    loginTypeApi = loginApi.login;
  }else if(navsActive.value === 'withCode'){
    loginObj.code = passwordForm.value.code;
    if(isPhoneLogin.value){
      loginObj.keyId = keyId.value;
      loginTypeApi = loginApi.loginByPhone;
    }else{
      loginTypeApi = loginApi.loginByEmail;
    }
  }

  changeRememberMe();

  loginTypeApi(loginObj).then((response:any)=>{
    if(response.code === 200){
      emits('loginSucceeded', true);
      piniaUserinfo.setUserinfo(response.data);
      piniaUserinfo.setHaslogged(true);
      dealKeys(response.data.token.key);
      // 获取钱包儿
      piniaUserinfo.queryWallet();
      // vip等级
      getUserVip();
      // 一些其他的东西
      getSportsByChannel();
      // 查询邮件和消息的个数
      piniaUserinfo.queryNoticeAndEmail();
    }
  }).finally(()=>{
    loading.value.passwordLoading = false;
  });
}

// 获取sports信息
const getSportsByChannel = () => {
  sportsApi.getSportsByChannel({}).then((response: any) => {
    if (response.code == 200) {
      console.log('运动信息',response);
      piniaUserinfo.setSportsInfo(response.data);
      // this.sportsChannel = res.data.gameChannel ? res.data.gameChannel : ''
      // localStorage.setItem(
      //   "BTIgameId",
      //   res.data.playId ? res.data.playId : ''
      // );
      // localStorage.setItem(
      //   "sportsChannel",
      //   res.data.gameChannel ? res.data.gameChannel : ''
      // );
      // 测试basha Sports
      //  this.sportsChannel = ''
      //  localStorage.setItem("sportsChannel",'');
    }
  })
}

// 获取vip等级
const getUserVip = () => {
  userinfoApi.getUserVip({}).then((res:any)=>{
    console.log("vip等级====", res)
  })
}

// 登录获取code
const getCodeOfLogin = () => {
  getLoginCodeDisabled.value = true;
  getCodeTimer(getLoginCodeTxt, getLoginCodeDisabled);
  getVerifiy(passwordForm.value);
}

// 记住密码
const changeRememberMe = () => {
  if(passwordForm.value.rememberPwd){
    window.localStorage.setItem('userName', passwordForm.value.userName);
    window.localStorage.setItem('password', passwordForm.value.password);
  }else{
    window.localStorage.removeItem('userName');
    window.localStorage.removeItem('password');
    window.localStorage.removeItem('rememberMe');
  }
  window.localStorage.setItem('rememberMe', String(passwordForm.value.rememberPwd));
}

// 重置密码code
const getCodeOfResetPassword = () => {
  getResetPasswordCodeDisabled.value = true;
  getCodeTimer(getResetPasswordCodeTxt, getResetPasswordCodeDisabled);
  getVerifiy(resetPasswordForm.value);
}

// 获取验证码
const getVerifiy = (whichForm: any) => {
  keyId.value = "";
  if(isPhoneLogin.value){
    // 手机验证码
    loginApi.getPhoneVerifiy({
      phone: `${whichForm.area}${whichForm.userName}`
    }).then((response:any)=>{
      if(response.code === 200){
        keyId.value = response.msg;
      }
      console.log("手机验证码", response)
    });
  }else{
    // 邮箱验证码
    loginApi.getEmailVerifiy({
      email: whichForm.userName
    }).then((response:any)=>{
      console.log("邮箱验证码", response)
    });
  }

}

// 注册code
const getCodeOfSignup = () => {
  getSignupCodeDisabled.value = true;
  getCodeTimer(getSignupCodeTxt, getSignupCodeDisabled);
}

// 倒计时
const getCodeTimer = (txt: any, disable: any) => {
  let timer:any = null;
  let countdown:number = 59;
  if(timer){ return; }
  const callback = function(){
    if(countdown <= 0){
      txt.value = t('home.PhoneGetCode');
      disable.value = false;
      clearInterval(timer);
    }else{
      txt.value = countdown--;
    }
  }
  callback();
  timer = setInterval(callback, 1000);
}

// 忘记密码
const forgetPassword = () => {
  type.value = 'forgetPasword';
  emits("changeType", type.value);
}

// 返回登录
const backToLogin = () => {
  type.value = 'login';
  stepActive.value = 1;
}
</script>

<style lang="scss" scoped>
@import url('./index.scss');
.z-dialog-wrapper-h5{
  .login-content{
    margin-top: var(--rem-200) !important;
    height: calc(100% - var(--rem-200)) !important;
    &.sign-up{
      padding-top: 0 !important;
    }
  }
}
</style>
